import React, {FC, useEffect} from 'react';
import {Link} from 'react-router-dom';
import './index.css';
import {UserAddOutlined} from '@ant-design/icons';
import {Button, Checkbox, Form, Input, Space} from 'antd';
import {useLocalStorageState} from 'ahooks';

/**
 * 注册表单类型
 */
type FieldType = {
	// 用户名
	username?: string;
	// 密码
	password?: string;
	// 确认密码
	confirm?: string;
	// 昵称
	nickname?: string;
	// 是否记住我
	remember?: boolean;
};

/**
 * 登录页面
 */
const Login: FC = () => {
	/* 用户Storage */
	const [moocUsernameStorage, setMoocUsernameStorage] = useLocalStorageState('mooc_username', undefined);
	/* 密码Storage */
	const [moocPasswordStorage, setMoocPasswordStorage] = useLocalStorageState('mooc_password', undefined);
	/* 获取form对象 */
	const [form] = Form.useForm();

	/**
	 * 页面加载调用函数
	 */
	useEffect(() => {
		console.log('useEffect -> form', form);
		// 如果本地Storage中用户名密码都不为空，则把数据回显到form表单中
		if(moocUsernameStorage && moocPasswordStorage){
			form.setFieldsValue({username: moocUsernameStorage, password: moocPasswordStorage});
		}
	}, [moocUsernameStorage, moocPasswordStorage, form]);

	/**
	 * 提交表单
	 */
	const onFinish = (values: FieldType) => {
		console.log('onFinish -> values', values);

		// 如果勾选了'记住我'，把数据存到本地Storage，否则清空本地Storage
		if(values.remember){
			setMoocUsernameStorage(values.username);
			setMoocPasswordStorage(values.password);
		}else{
			setMoocUsernameStorage(undefined);
			setMoocPasswordStorage(undefined);
		}
	};

	return (
		<div className="login">
			<h1 className="login-title">
				<UserAddOutlined/>&nbsp;用户登录
			</h1>
			<div className="login-form">
				<Form
					labelCol={{span: 6}}
					wrapperCol={{span: 16}}
					initialValues={{remember: true}}
					onFinish={onFinish}
					form={form}
				>
					<Form.Item<FieldType>
						label="用户名"
						name="username"
						rules={[
							{required: true, message: '请输入用户名！'},
							{type: 'string', min: 4, max: 18, message: '用户名长度在 4-18 之间！'},
							{pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能由字母和数字和下划线组成！'},
						]}
					>
						<Input/>
					</Form.Item>

					<Form.Item<FieldType>
						label="密码"
						name="password"
						rules={[
							{required: true, message: '请输入密码！'},
							{type: 'string', min: 4, max: 18, message: '密码长度在 4-18 之间！'},
						]}
					>
						<Input.Password/>
					</Form.Item>

					<Form.Item<FieldType>
						name="remember"
						valuePropName="checked"
						wrapperCol={{offset: 6, span: 16}}
					>
						<Checkbox>
							记住我
						</Checkbox>
					</Form.Item>

					<Form.Item
						wrapperCol={{offset: 10, span: 16}}
					>
						<Space>
							<Button
								type="primary"
								htmlType="submit"
							>
								登录
							</Button>
							<Link to="/register" style={{fontSize: 10}}>
								去注册
							</Link>
						</Space>
					</Form.Item>
				</Form>
			</div>
		</div>
	);
};

export default Login;